package org.spring.beans.factory.annotation;

import java.lang.reflect.Field;

import org.spring.beans.factory.BeanCreateException;
import org.spring.beans.factory.config.AutoWireCapableBeanFactory;
import org.spring.beans.factory.config.DependencyDescriptor;
import org.spring.util.ReflectionUtils;

public class AutowiredFieldElement extends InjectionElement {
	private boolean required;

	public AutowiredFieldElement(Field filed, boolean required, AutoWireCapableBeanFactory beanFactory) {
		super(filed, beanFactory);
		this.required = required;
	}

	@Override
	public void inject(Object target) {
		Field field = getField();
		try {
			DependencyDescriptor descriptor = new DependencyDescriptor(field, this.required);
			Object object = this.factory.resolveDependecy(descriptor);
			if (object != null) {
				ReflectionUtils.makeAccessible(field);
				field.set(target, object);
			}
		} catch (Exception e) {
			throw new BeanCreateException("Could not autowire field: " + field, e);
		}
	}

	public Field getField() {
		return (Field) this.member;
	}

}
